<template>
  <div class="container">
    <el-row class="p-t-15">
      <el-col>
        <el-tabs v-model="query.lan" type="card">
          <el-tab-pane
            v-for="tab in TABS"
            :key="tab.value"
            :label="$t(tab.label)"
            :name="tab.value"
          />
        </el-tabs>
      </el-col>
    </el-row>

    <div class="box-card">
      <el-card>
        <div class="clearfix">
          <el-row class="search-content">
            <el-col>
              <label>{{$t('topic_name')}}：</label>
              <el-input
                v-model.trim="query.specialName"
                size="small"
                class="w-200"
                clearable
              />
              <label>{{$t('user_data_time_period')}}：</label>
              <date-range-picker
                v-model="queryDateRange"
                :clearable="false"
                class="w-240"
                size="small"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="~"
                :start-placeholder="$t('start_date')"
                :end-placeholder="$t('end_date')"
                value-format="yyyy-MM-dd"
              />
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="fetchAndSetupSubjectList({ currentPage: 1 })"
              >
                {{$t('search')}}
              </el-button>
            </el-col>
          </el-row>
          <div class="button-list">
            <el-button size="small" @click="exportToExcel">{{$t('export_doc')}}</el-button>
          </div>
        </div>
        <div class="clearfix">
          <el-button-group class="sort-group">
            <el-button
              v-for="sortField of SORT_FIELDS"
              :key="sortField.value"
              :class="{ 'sort-color': query.sortId === sortField.value }"
              @click="sortSubjectList(sortField.value)"
            >
              {{ $t(sortField.label) }}
              <span class="sort-arrow">
                <i
                  v-for="item in SORT_DIR_OPTIONS"
                  :key="item.value"
                  :class="[
                    {
                      'defalut-color':
                        query.sortId === sortField.value &&
                        query.sortOrder === item.value
                    },
                    `el-icon-caret-${item.arrow}`,
                    `sort-arrow__${item.arrow}`
                  ]"
                />
              </span>
            </el-button>
          </el-button-group>
        </div>
        <div class="list-content">
          <el-table
            v-loading="listLoading"
            id="newsTable"
            ref="newsTable"
            :data="formatTableData"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column
              v-for="header in HEADERS"
              :key="header.prop"
              :prop="header.prop"
              :label="$t(header.label)"
            />
            <el-table-column prop="id" :label="$t('operation')" width="260">
              <template slot-scope="scope">
                <router-link
                  :to="{
                    path: '/thematicSectionAnalysis/singleThematicStatement',
                    query: { id: scope.row.id, lan: query.lan }
                  }"
                  target="_blank"
                >
                  <el-button type="primary" size="mini">{{$t('thematic_analysis')}}</el-button>
                </router-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="block fr">
            <el-pagination
              :current-page.sync="pagination.currentPage"
              :page-sizes="[20, 50, 100]"
              :page-size.sync="pagination.pageSize"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="fetchAndSetupSubjectList({ currentPage: 1 })"
              @current-change="fetchAndSetupSubjectList"
            />
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { format, subDays } from 'date-fns';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';
import { getSpecialSubjectList } from '@/api/subject.js';
import '@/assets/css/common/style.scss';
import { excludeKeys } from '@/utils/index';

const TABS = [
  { label: 'english_cambodian', value: 'km-KH' },
  { label: 'chinese', value: 'zh-Hans' }
];

const EMPTY_PAGINATION = {
  currentPage: 1,
  pageSize: 20,
  total: 0
};

const SORT_DIR_OPTIONS = [
  { arrow: 'bottom', value: '1' },
  { arrow: 'top', value: '-1' }
];

const SORT_DIR = SORT_DIR_OPTIONS.map(t => t.value);

const SORT_FIELDS = [
  { label: 'add_time', value: '1' },
  { label: 'visit_uv', value: 2 },
  { label: 'content_read', value: 3 },
  { label: 'exposure_read_conversions', value: 4 }
];

const EMPTY_QUERY = {
  lan: TABS[0].value,
  beginDate: format(subDays(new Date(), 6), 'yyyy-MM-dd'),
  endDate: format(new Date(), 'yyyy-MM-dd'),
  sortId: SORT_FIELDS[0].value,
  sortOrder: SORT_DIR[0]
};

const HEADERS = [
  { label: 'topic_name', prop: 'specialName' },
  { label: 'add_time', prop: 'createTimeFmt' },
  { label: 'hotness', prop: 'heatValue' },
  { label: 'content_volume', prop: 'contentCount' },
  { label: 'visited_pv', prop: 'pv' },
  { label: 'visit_uv', prop: 'uv' },
  { label: 'content_read', prop: 'contentRead' },
  { label: 'exposure_read_conversions', prop: 'contentReadRate' }
];

export default {
  mixins: [dateShortcutKeyJS],

  data() {
    return {
      HEADERS,
      TABS,
      SORT_FIELDS,
      SORT_DIR_OPTIONS,
      tableData: [],
      listLoading: false,
      query: { ...EMPTY_QUERY },
      pagination: { ...EMPTY_PAGINATION }
    };
  },

  computed: {
    queryDateRange: {
      get() {
        return [this.query.beginDate, this.query.endDate];
      },
      set(value) {
        [this.query.beginDate, this.query.endDate] = value;
      }
    },

    formatTableData() {
      return this.formatRows(this.tableData);
    },

    currentTab() {
      return TABS.find(t => t.value === this.query.lan);
    }
  },

  watch: {
    [`query.lan`](lan) {
      this.pagination = { ...EMPTY_PAGINATION };
      this.query = { lan, ...excludeKeys(EMPTY_QUERY, 'lan') };
      this.fetchAndSetupSubjectList();
    }
  },

  mounted() {
    this.fetchAndSetupSubjectList();
  },

  methods: {
    formatRows(rows) {
      return rows.map(t => ({
        ...t,
        createTimeFmt: format(t.createTime, 'yyyy-MM-dd HH:mm:ss')
      }));
    },

    async fetchSubjectList(options = {}) {
      try {
        this.listLoading = true;
        const params = {
          ...this.query,
          ...this.$pick(['currentPage', 'pageSize'])(this.pagination),
          ...options
        };
        const res = await getSpecialSubjectList(params);
        if (res.code === 200) {
          return res.data;
        } else {
          const msg = res.msg || res.data;
          this.$message({ type: 'error', message: msg });
          throw new Error(msg);
        }
      } finally {
        this.listLoading = false;
      }
    },

    async fetchAndSetupSubjectList(options = {}) {
      const data = await this.fetchSubjectList(options);
      this.tableData = data.rows;
      this.pagination.total = data.total;
    },

    sortSubjectList(sortId) {
      if (sortId === this.query.sortId) {
        const currentIndex = SORT_DIR.indexOf(this.query.sortOrder);
        const nextIndex = (currentIndex + 1) % SORT_DIR.length;
        this.query.sortOrder = SORT_DIR[nextIndex];
      } else {
        this.query.sortId = sortId;
        this.query.sortOrder = SORT_DIR[0];
      }
      this.fetchAndSetupSubjectList();
    },

    async exportToExcel() {
      const headers = HEADERS.map(t => this.$t(t.label));
      const props = HEADERS.map(t => t.prop);
      const { rows: data } = await this.fetchSubjectList({
        currentPage: 1,
        pageSize: this.pagination.total
      });
      const filename = `${this.$t(this.currentTab.label)}-
      ${this.query.beginDate}~${this.query.endDate}`
      exportJsonToExcel(
        headers,
        formatJson(props, this.formatRows(data)),
        filename
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.w-150 {
  width: 150px;
}
/* 标签盒子 */
.box-card {
  margin: 0 0 20px 0;
}
.w-200 {
  width: 200px;
}
/* 表格tab */
.search-content {
  float: left;
}
.button-list {
  float: right;
}
.list-content {
  overflow: hidden;
}
.block {
  margin: 20px 0 0 0;
}
// 排序+批量操作
.sort-group {
  float: right;
  margin-top: 12px;
}

// 排序箭头
.sort-arrow {
  padding-right: 10px;
  &__top {
    position: absolute;
    top: 8px;
  }
  &__bottom {
    position: absolute;
    top: 15px;
  }
}

//箭头默认颜色
.defalut-color {
  color: #606266;
}

.sort-color {
  color: #409eff !important;
}
</style>
